import 'dart:io';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/file_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/widget/photo_view.dart';
import 'package:yuan_hang_app/widget/video_preview.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../http/api.dart';
import '../../http/http_utils.dart';
import '../../res/w_constant.dart';
import '../../utils/router_helper.dart';
import '../../widget/status_btn.dart';
import '../../widget/w_toast.dart';

class NoticeDetailPage extends StatefulWidget {
  int noticeId;

  NoticeDetailPage({super.key, required this.noticeId});

  @override
  BaseState<NoticeDetailPage> createState() => _NoticeDetailPageState();
}

class _NoticeDetailPageState extends BaseState<NoticeDetailPage> {
  List picList = [];

  Map noticeInfo = {};

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "通告详情",
      resizeToBottomInset: true,
      child:  ListView(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        children: [
          _cardItem(
              StringUtils.safeGetValue(noticeInfo["notificationTitle"]),
              _noticeMsgInfo()),
          _cardItem("附件区", _partFileInfo()),
        ],
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    HttpUtils()
        .get("${Api.getNoticeMessageDetail}?notificationId=${widget.noticeId}")
        .then((value) {
      if (value.resultCode == 200) {
        noticeInfo = value.data;
        //   List<dynamic> fileAddressList = value.data["fileAddress"];
        // 使用where和map结合来确保只处理类型正确的元素
        picList = value.data["fileAddress"];
        // .where((element) => element is Map && element.containsKey("fileUrl") && element["fileUrl"] is String)
        // .map((address) => address["fileUrl"])
        // .toList();
        print("---------------------$picList");

        setState(() {});

        ///调用已读接口
        HttpUtils()
            .get(
                "${Api.updateNoticeStatus}?notificationId=${widget.noticeId}&userId=${WConstant().userInfo.userId}")
            .then((value) => {});
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    });
  }

  Container _cardItem(String label, Widget child, {double bottom = 0}) {
    return Container(
      margin: EdgeInsets.only(
          top: 10.px, left: 15.px, right: 15.px, bottom: bottom.px),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10.px)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 48.px,
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Expanded(
                    child: Row(children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                    marginRight: 10.px,
                  ),
                  Flexible(
                      child: WText(
                    overflow: TextOverflow.ellipsis,
                    label,
                    style: TextStyle(
                        fontSize: WDimens.tsLarge,
                        color: WColors.mainTextColor,
                        fontWeight: FontWeight.bold),
                  )),
                  Offstage(
                    offstage: label == "附件区",
                    child: StatusBtn(
                      margin: EdgeInsets.only(left: WDimens.tsXXLarge),
                      height: 30.px,
                      width: 68.px,
                      color: WColors.border,
                      fontColor: WColors.mainTextColor,
                      text: StringUtils.safeGetValue(
                          noticeInfo['notificationType']),
                      isItemBtn: true,
                    ),
                  ),
                ]))
              ],
            ),
          ),
          child
        ],
      ),
    );
  }

  ///公告信息
  Container _noticeMsgInfo() {
    return Container(
        padding: EdgeInsets.only(
          left: 16.px,
        ),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              WText(
                  StringUtils.safeGetValue(noticeInfo['notificationContent'],
                      placeHolder: "主要内容：-"),
                  style: TextStyle(
                    fontSize: WDimens.tsMedium,
                    color: WColors.mainTextColor,
                  )),
              SizedBox(height: 8.px),
              WText(
                  "通告编号： ${StringUtils.safeGetValue(noticeInfo['notificationNo'], placeHolder: "-")}",
                  style: TextStyle(
                    fontSize: WDimens.tsLabel,
                    color: WColors.mainTextColor,
                  )),
              SizedBox(height: 8.px),
              WText(
                  "发布部门： ${StringUtils.safeGetValue(noticeInfo['publishOrgName'], placeHolder: "-")}",
                  style: TextStyle(
                    fontSize: WDimens.tsLabel,
                    color: WColors.mainTextColor,
                  )),
              SizedBox(height: 8.px),
              WText("发布时间：${StringUtils.safeGetValue(noticeInfo['timing'])}",
                  style: TextStyle(
                    fontSize: WDimens.tsLabel,
                    color: WColors.hintTextColor,
                  )),
              SizedBox(height: 8.px),
              WText(
                  "结束时间：${StringUtils.safeGetValue(noticeInfo['endTime'], placeHolder: "-")}",
                  style: TextStyle(
                    fontSize: WDimens.tsLabel,
                    color: WColors.hintTextColor,
                  )),
              SizedBox(height: 8.px),
            ]));
  }

  Future<void> _launchURL(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw '无法打开 $url';
    }
  }

  ///附件区
  ListView _partFileInfo() {
    List imgList = getImgList();
    return ListView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        itemCount: picList.length,
        itemBuilder: (context, index) => GestureDetector(
              onTap: () async {
                String type = getType(picList[index]["fileUrl"]);
                String url = picList[index]["fileUrl"];
                if (type == "img") {
                  int myIndex = getPicIndex(imgList, url);
                  RouteHelper.pushWidget(
                      context, PhotoView(imgs: imgList, currentIndex: myIndex));
                } else if (type == "mp4") {
                  if (url.contains(".avi")) {
                    String time = DateUtil.formatDate(DateTime.now(),
                        format: "yyyyMMddHHmmss.mp4");
                    File? file = await FileUtils.getAppFile(time);
                    if (file == null) {
                      return;
                    }
                    showLoading();
                    HttpUtils().downloadFile(url, file.path).then((res) {
                      hideLoading();
                      RouteHelper.pushWidget(
                          context,
                          VideoPreview(
                            url: file.path,
                          ));
                    }).catchError((e){
                      hideLoading();
                    });
                  } else {
                    RouteHelper.pushWidget(
                        context,
                        VideoPreview(
                          url: url,
                        ));
                  }
                } else if (type == "zip") {
                  Toast.toast("请在web端下载查看");
                } else {
                  _launchURL(url);
                }
              },
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 5.px),
                padding: EdgeInsets.symmetric(vertical: 8.px),
                decoration: BoxDecoration(
                    border: picList.length - 1 == index
                        ? null
                        : Border(
                            bottom: BorderSide(
                                color: WColors.border, width: 0.5.px))),
                child: Row(
                  children: <Widget>[
                    Image.asset(
                      "images/${getType(picList[index]["fileUrl"])}.png",
                      width: 30.px,
                    ),
                    SizedBox(
                      width: 10.px,
                    ),
                    Flexible(
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: WText(
                          overflow: TextOverflow.ellipsis,
                          picList[index]["fileName"],
                          style: TextStyle(
                              fontSize: WDimens.tsLabel,
                              color: WColors.subTextColor),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ));
  }

  List getImgList() {
    return picList
        .where((item) => getType(item["fileUrl"]) == "img")
        .map((img) => img["fileUrl"])
        .toList();
  }

  int getPicIndex(list, url) {
    for (int i = 0; i < list.length; i++) {
      if (list[i] == url) {
        return i;
      }
    }
    return 0;
  }

  String getType(String url) {
    if (url.contains(".mp4") || url.contains(".avi")) {
      return "mp4";
    } else if (url.contains(".rar") || url.contains(".zip")) {
      return "zip";
    }
    if (url.contains(".xls") || url.contains(".xlsx")) {
      return "excel";
    } else if (url.contains(".doc") || url.contains(".docx")) {
      return "word";
    } else if (url.contains(".ppt") || url.contains(".pptx")) {
      return "ppt";
    } else if (url.contains(".txt")) {
      return "txt";
    } else if (url.contains(".pdf")) {
      return "pdf";
    } else {
      return "img";
    }
  }
}
